package com.ruoyi.miniprogram.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.dto.MiniProgramUserDto;
import com.ruoyi.common.core.domain.entity.miniprogram.MiniAddress;
import com.ruoyi.common.core.domain.entity.system.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.manager.AsyncManager;
import com.ruoyi.manager.factory.AsyncFactory;
import com.ruoyi.miniprogram.mapper.MiniAddressMapper;
import com.ruoyi.miniprogram.mapper.MiniUserAddressMapper;
import com.ruoyi.miniprogram.service.IMiniprogramUserService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class MiniprogramUserServiceImpl implements IMiniprogramUserService {

    @Autowired
    private TokenService tokenService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private MiniAddressMapper miniAddressMapper;

    @Resource
    private MiniUserAddressMapper miniUserAddressMapper;

    @Override
    public void logout() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
        }
    }

    @Override
    public int updateMiniprogramUser(MiniProgramUserDto userDto) {
        return sysUserMapper.updateMiniprogramUser(userDto);
    }

    @Override
    @Transactional
    public int insertAddress(MiniAddress address) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        int row = miniAddressMapper.insertAddress(address);
        if (row > 0) {
            boolean isDefaultAddress = address.isDefaultAddress();
            if (isDefaultAddress) { //用户将当前地址设置为默认地址
                SysUser sysUser = new SysUser(userId);
                sysUser.setDefaultAddressId(address.getAddressId());
                sysUserMapper.updateUser(sysUser);
            }
            //将用户id与地址id进行关联
            miniUserAddressMapper.insertUserAddress(userId, address.getAddressId());
        }
        return row;
    }

    @Override
    public List<MiniAddress> getAddressList() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);

        List<MiniAddress> addressList = miniAddressMapper.selectAddressListByUserId(userId);
        Long defaultAddressId = sysUser.getDefaultAddressId();
        addressList.forEach(address -> {
            if (Objects.equals(defaultAddressId, address.getAddressId())) {
                address.setDefaultAddress(true);
            } else {
                address.setDefaultAddress(false);
            }
        });

        return addressList;
    }

    @Override
    @Transactional
    public int updateAddress(MiniAddress address) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);

        int row = miniAddressMapper.updateAddress(address);
        if (address.isDefaultAddress()) {
            sysUser.setDefaultAddressId(address.getAddressId());
            sysUserMapper.updateUser(sysUser);
        } else {
            Long originDefaultAddressId = sysUser.getDefaultAddressId();
            if (Objects.equals(originDefaultAddressId, address.getAddressId())) {
                sysUser.setDefaultAddressId(0L);
                sysUserMapper.updateUser(sysUser);
            }
        }

        return row;
    }

    @Override
    public MiniAddress getAddressInfo(Long addressId) {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);

        MiniAddress address = miniAddressMapper.selectAddressById(addressId);
        if (Objects.equals(sysUser.getDefaultAddressId(), addressId)) {
            address.setDefaultAddress(true);
        } else {
            address.setDefaultAddress(false);
        }

        return address;
    }

    @Override
    public int deleteAddress(Long addressId) {
        return miniAddressMapper.deleteAddress(addressId);
    }
}
